from app.extensions import get_db
from app.models.Clas import Clas
from app.services.StudentService import StudentService
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from app.schames.Student import StudentSchema, StudentCreate

student_route = APIRouter(prefix="/studnet", tags=["学生管理"])

@student_route.get("/", summary="搜索学生")
def get_by_keyword(keyword:str = ""):
    with get_db() as db: # 链接数据库
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.get_by_keyword(keyword)
        return JSONResponse(
            content={
                "data": [StudentSchema.model_validate(item).model_dump() for item in response["data"]],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

@student_route.post("/", summary="增加学生")
def add_student(stu: StudentCreate):
    with get_db() as db: # 链接数据库
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.add_student(stu.clas_id, stu.name, stu.gender)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

@student_route.put("/{stu_id}", summary="修改学生")
def update_student(stu_id, stu: StudentCreate):
    with get_db() as db: # 链接数据库
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.update_student(stu_id, stu.name, stu.gender, stu.clas_id)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )

@student_route.delete("/{stu_id}", summary="删除学生")
def delete_student(id: int):
    with get_db() as db: # 链接数据库
        # 创建service对象并调用服务
        svc = StudentService(db)
        response = svc.delete_student(id)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )